package com.kang.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kang.base.LoginDataBase;
import com.kang.entity.Reply;
import com.kang.entity.SysUser;
import com.kang.mapper.ReplyMapper;
import com.kang.mapper.UserMapper;
import com.kang.service.ReplyService;
import com.kang.util.TokenToUserId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ReplyServiceImpl extends ServiceImpl<ReplyMapper, Reply> implements ReplyService {

    @Autowired
    private ReplyMapper replyMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Override
    public Integer insertReply(Reply reply, HttpServletRequest request) {
        /*
         * 一级评论时last_id传null 还传essay_id
         * 当在评论下回复时，传回复人的last_id ,last_name essay_id
         */
        reply.setCreateTime(new Date());
        reply.setUpdateTime(new Date());
        String token = request.getHeader("token");
        String ObjectJson = stringRedisTemplate.opsForValue().get("login:token:" + token);
        LoginDataBase loginDataBase = JSON.parseObject(ObjectJson, LoginDataBase.class);
        assert loginDataBase != null;
        SysUser user = loginDataBase.getUser();
        reply.setUserId(user.getId());
        reply.setUsername(user.getUsername());
        reply.setUserUrl(user.getHeadUrl());
        int insert = replyMapper.insert(reply);
        if (insert == 1) {
            stringRedisTemplate.opsForValue().increment("user:reply:" + reply.getEssayId());
        }
        return insert;
    }

    @Override
    public Integer deleteReply(Integer id) {
        QueryWrapper<Reply> wrapper = new QueryWrapper<>();
        wrapper.eq("last_id",id).or().eq("id",id);
        int delete = replyMapper.delete(wrapper);
        if (delete == 1) {
            Reply reply = baseMapper.selectById(id);
            stringRedisTemplate.opsForValue().decrement("user:reply:" + reply.getEssayId());
        }

        return delete;
    }

    @Override
    public List<Reply> getReplyList(Integer essayId) {
        QueryWrapper<Reply> wrapper = new QueryWrapper<>();
        wrapper.eq("essay_id",essayId);
        wrapper.last("order by create_time desc");
        //查出所以评论
        List<Reply> replyList = replyMapper.selectList(wrapper);
        //分出第一层和第二层评论
        List<Reply> one = replyList.stream().filter(v -> v.getLastId() == null).collect(Collectors.toList());
        List<Reply> two = replyList.stream().filter(v -> v.getLastId() != null).collect(Collectors.toList());
        List<Reply> parent = findParent(one, two);
        for (Reply reply : parent) {
            if (reply.getChildren().size() != 0) {
                List<Reply> children = reply.getChildren();
                for (Reply child : children) {
                    Reply reply1 = replyMapper.selectById(child.getLastId());
                    SysUser user = userMapper.selectById(reply1.getUserId());
                    child.setLastName(user.getUsername());
                    child.setLastUrl(user.getHeadUrl());
                }
                reply.setChildren(children);
            }
        }
        return parent;
    }

    public List<Reply> findParent(List<Reply> fatherList , List<Reply> childrenList) {
        for (Reply reply : fatherList) {
            List<Reply> resultList = new ArrayList<>();
            //递归处理
            findChildren(reply,childrenList,resultList);
            reply.setChildren(resultList);
        }


        return fatherList;
    }

    public void findChildren(Reply parent,List<Reply> childrenList , List<Reply> resultList) {
        //找出当前评论下的所有子级
        List<Reply> collect = childrenList.stream().filter(v -> v.getLastId().equals(parent.getId())).collect(Collectors.toList());

        //遍历所有子级 是否存在更子级的
        for (Reply reply1 : collect) {
            List<Reply> replyList = childrenList.stream().filter(v -> v.getLastId().equals(reply1.getId())).collect(Collectors.toList());
            if (replyList.size() != 0) {
                findChildren(reply1,childrenList,resultList);
            }

            resultList.add(reply1);
        }
    }


}
